package com.xiaowu.house.filter;



import com.xiaowu.house.config.IgnoreWhiteProperties;
import com.xiaowu.house.constants.SecurityConstants;
import com.xiaowu.house.constants.TokenConstants;
import com.xiaowu.house.domain.ResultCode;
import com.xiaowu.house.service.RedisService;
import com.xiaowu.house.service.TokenService;
import com.xiaowu.house.utils.JwtUtil;
import com.xiaowu.house.utils.ServletUtil;
import com.xiaowu.house.utils.StringUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 白名单配置类
     */
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;

    @Autowired
    private RedisService redisService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String url = request.getURI().getPath();
        if (StringUtil.matches(url, ignoreWhiteProperties.getWhites())) {
            return chain.filter(exchange);
        }

        String token = getToken(request);

        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, ResultCode.TOKEN_EMPTY);
        }

        Claims claims = JwtUtil.parseToken(token);
        if (claims == null) {
            return unauthorizedResponse(exchange, ResultCode.TOKEN_INVALID);
        }

        String userKey = JwtUtil.getUserKey(claims);
        boolean isLogin = redisService.hasKey(getTokenKey(userKey));

        if (!isLogin) {
            return unauthorizedResponse(exchange, ResultCode.LOGIN_STATUS_OVERTIME);
        }

        String userId = JwtUtil.getUserId(claims);
        String userName = JwtUtil.getUserName(claims);
        String userFrom = JwtUtil.getUserFrom(claims);
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName)) {
            return unauthorizedResponse(exchange, ResultCode.TOKEN_CHECK_FAILED);
        }

        ServerHttpRequest.Builder mutate = request.mutate();
        addHeader(mutate, SecurityConstants.USER_KEY, userKey);
        addHeader(mutate, SecurityConstants.USER_ID, userId);
        addHeader(mutate, SecurityConstants.USERNAME, userName);
        addHeader(mutate, SecurityConstants.USER_FROM, userFrom);

        return chain.filter(exchange.mutate().request(mutate.build()).build());

    }

    private String getTokenKey(String userKey) {
        return TokenConstants.LOGIN_TOKEN_KEY + userKey;
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, ResultCode resultCode) {
        log.error("[鉴权处理异常]请求路径:{}", exchange.getRequest().getPath());
        int retCode = Integer.parseInt(String.valueOf(resultCode.getCode()).substring(0, 3));
        return ServletUtil.webFluxResponseWriter(exchange.getResponse(), HttpStatus.valueOf(retCode), resultCode.getMsg(), resultCode.getCode());
    }

    private String getToken(ServerHttpRequest request) {
        return request.getHeaders().getFirst(SecurityConstants.AUTHENTICATION);
    }

    private void addHeader (ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) return;
        String valueStr = value.toString();
        String valueEncode = ServletUtil.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
